﻿//---------------------------------------------------------------------------------
// Copyright 2011 Microsoft Corporation
// Licensed under the Microsoft Public License (MS-PL) (the "License"); 
// You may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.opensource.org/licenses/ms-pl.html
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR 
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR 
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
// MERCHANTABLITY OR NON-INFRINGEMENT. 
// See the Microsoft Public License (MS-PL) for the specific language governing 
// permissions and limitations under the License.
//---------------------------------------------------------------------------------

using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Microsoft.Telco.Controls
{
    /// <summary>
    /// Country flag selector.
    /// </summary>
    public partial class CountryPicker : UserControl
    {
        #region events
        /// <summary>
        /// Raised when country selection changes. Payload is country code.
        /// </summary>
        public event Action<string> SelectedCountryChanged;
        #endregion

        #region properties

        ObservableCollection<Country> countries;
        /// <summary>
        /// Gets the selected country code.
        /// </summary>
        /// <value>The selected country code.</value>
        public string SelectedCountryCode
        {
            get
            {
                return listCountries.SelectedItem != null ? (listCountries.SelectedItem as Country).Code : string.Empty;
            }
        }
       
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="CountryPicker"/> class.
        /// </summary>
        public CountryPicker()
        {
            // Required to initialize variables
            InitializeComponent();
            if (!ControlHelper.PopupTracker.ContainsKey("popupCountries"))
            {
                ControlHelper.PopupTracker.Add("popupCountries", popupCountries);
            }
            Loaded += CountryPicker_Loaded;
        }

        #region dependency properties

        /// <summary>
        /// Gets or sets the height of the phone number control.
        /// </summary>
        /// <value>The height of the phone number control.</value>
        public double PhoneNumberControlHeight
        {
            get { return (double)GetValue(PhoneNumberControlHeightProperty); }
            set { SetValue(PhoneNumberControlHeightProperty, value); }
        }

        /// <summary>
        /// Using a DependencyProperty as the backing store for PhoneNumberControlHeight.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty PhoneNumberControlHeightProperty =
            DependencyProperty.Register("PhoneNumberControlHeight", typeof(double), typeof(CountryPicker),
            new PropertyMetadata(40.0D,new PropertyChangedCallback(PhoneNumberControlHeightChangedCallback)));

        ///// <summary>
        ///// Gets or sets the country text font family.
        ///// </summary>
        ///// <value>The country text font family.</value>
        //public FontFamily CountryTextFontFamily
        //{
        //    get { return (FontFamily)GetValue(CountryTextFontFamilyProperty); }
        //    set { SetValue(CountryTextFontFamilyProperty, value); }
        //}

        ///// <summary>
        ///// Using a DependencyProperty as the backing store for CountryTextFontFamily.  This enables animation, styling, binding, etc...
        ///// </summary>
        //public static readonly DependencyProperty CountryTextFontFamilyProperty =
        //    DependencyProperty.Register("CountryTextFontFamily", typeof(FontFamily), typeof(CountryPicker),
        //    new PropertyMetadata(new FontFamily("Arial")));

        ///// <summary>
        ///// Gets or sets the size of the country text font.
        ///// </summary>
        ///// <value>The size of the country text font.</value>
        //public double CountryTextFontSize
        //{
        //    get { return (double)GetValue(CountryTextFontSizeProperty); }
        //    set { SetValue(CountryTextFontSizeProperty, value); }
        //}

        ///// <summary>
        ///// Using a DependencyProperty as the backing store for CountryTextFontFamily.  This enables animation, styling, binding, etc...
        ///// </summary>
        //public static readonly DependencyProperty CountryTextFontSizeProperty =
        //    DependencyProperty.Register("CountryTextFontSize", typeof(double), typeof(CountryPicker),
        //    new PropertyMetadata(12.0D));

        ///// <summary>
        ///// Gets or sets the country text foreground.
        ///// </summary>
        ///// <value>The country text foreground.</value>
        //public Brush CountryTextForeground
        //{
        //    get { return (Brush)GetValue(CountryTextForegroundProperty); }
        //    set { SetValue(CountryTextForegroundProperty, value); }
        //}

        ///// <summary>
        ///// Using a DependencyProperty as the backing store for CountryTextFontFamily.  This enables animation, styling, binding, etc...
        ///// </summary>
        //public static readonly DependencyProperty CountryTextForegroundProperty =
        //    DependencyProperty.Register("CountryTextForeground", typeof(Brush), typeof(CountryPicker),
        //    new PropertyMetadata(new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x00, 0x00))));
        #endregion

        #region public methods
         /// <summary>
        /// Selects the flag from country code.
        /// </summary>
        /// <param name="code">The code.</param>
        public void SelectFlagFromCountryCode(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {

            }
            else
            {
                //countryImage.Source = new BitmapImage(new Uri("images/Unknown.png", UriKind.Relative));
            }
        }
        #endregion

        #region event handlers

        private void CountryPicker_Loaded(object sender, RoutedEventArgs e)
        {
            countries = CountryHelper.GetCountries();
            listCountries.Items.Clear();
            listCountries.ItemsSource = countries;
            foreach (var country in countries)
            {
                //TODO: decide default country based on localization
                if (country.ShortName == "US")
                {
                    listCountries.SelectedItem = country;
                    SetCountryImage(country.ImageUrl);
                    break;
                }
            }
        }

        private void bdrCountryPicker_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            bool shouldOpen = !popupCountries.IsOpen;
            if (shouldOpen)
            {
                popupCountries.HorizontalOffset = 0; //CountryHelper.GetAbsolutePosition(bdrCountryPicker, Corner.LeftBottom).X;
                popupCountries.VerticalOffset = PhoneNumberControlHeight; //CountryHelper.GetAbsolutePosition(bdrCountryPicker, Corner.LeftBottom).Y;
            }
            popupCountries.IsOpen = shouldOpen;
            e.Handled = true;
        }

        private static void PhoneNumberControlHeightChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            CountryPicker countryPicker = (CountryPicker)obj;
            countryPicker.PhoneNumberControlHeight = 40.0D;
        }

        private void listCountries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            popupCountries.IsOpen = false;
            var selectedCountry = (Country)listCountries.SelectedItem;
            if (SelectedCountryChanged != null && listCountries.SelectedItem != null)
            {
                SelectedCountryChanged(selectedCountry.Code);
                SetCountryImage(selectedCountry.ImageUrl);
            }
        }
       
        #endregion

        #region helper methods

        private void SetCountryImage(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                url = "images/Unknown.png";
            }
            countryImage.Source = new BitmapImage(new Uri(url, UriKind.Relative));
        }
        #endregion
    }
}